#include<unistd.h>
#include<iostream>
#include<pthread.h>
#include<vector>

#define MAX 3

int date=10;

class My_Pthread
{
public:
    My_Pthread(pthread_t id,int name,pthread_mutex_t*mute)
    :_id(id),_name(name),_mute(mute)
    {}

    //线程ID
    pthread_t _id=0;
    //线程名
    int _name;
    //锁
    pthread_mutex_t* _mute;
};

//线程任务函数
void* handle(void* arg)
{
    //防止线程跑太快
   usleep(1000);
    //强转
    My_Pthread* ptr=(My_Pthread*)arg;

    while(true)
    {
        {
            //获取锁
            pthread_mutex_lock(ptr->_mute);
            if(date>0)
            {
                std::cout<<"线程编号:"<<(ptr->_name)<<" "<<"date:"<<date<<std::endl;
                date--;
            }
            else
            {
                //释放锁
                pthread_mutex_unlock(ptr->_mute);
                break;
            }
            //释放锁
            pthread_mutex_unlock(ptr->_mute);
        }
        usleep(200);
    }

    return (void*)ptr;
}

int main()
{
    //定义锁
    pthread_mutex_t mute;
    //初始化锁
    pthread_mutex_init(&mute,NULL);

    //用指针来存取线程信息
    std::vector<My_Pthread*> pthread_pointer;

    for(int i=1;i<=MAX;i++)
    {
         pthread_t id;
        //线程执行任务
        My_Pthread* ptr=new My_Pthread(id,i,&mute);
        //存储线程数据
        pthread_pointer.push_back(ptr);

        pthread_create(&id,NULL,handle,(void*)ptr);
        ptr->_id=id;
    }

    //线程等待
    for(int i=0;i<MAX;i++)
    {
        void* ptr;
        pthread_join(pthread_pointer[i]->_id,&ptr);
        //std::cout<<(((My_Pthread*)ptr)->_name)<<"："<<(((My_Pthread*)ptr)->_id)<<std::endl;
    }
    //回收空间
    for(int i=0;i<MAX;i++)
    {
        delete pthread_pointer[i];
    }

    return 0;
}